﻿import com.dinmax.isolution.*
import com.dinmax.flash.utilities.communication.TextParser;
import com.dinmax.flash.utilities.communication.TextParserListener;
import com.dinmax.flash.utilities.xml.XMLAction;

class Communication
extends XMLSocket {
	
	public static var DUMMY:Boolean = false;
	private static var comm:Communication;
	private var listener:CommunicationListener;
	private var IP:String;
	private var PORT:Number;
	
	
	public static function getInstance(listener:CommunicationListener):Communication {
		if(comm){ 
			return comm;
		} else {
			comm = new Communication(listener);
			return comm;
		}
	};
	
	function Communication(listener:CommunicationListener){
		this.listener = listener;
		this.getData();
		return;		
	}
	
	public function getIP():String {
		return IP;
	}

	private function setIP(IP:String):Void {
		this.IP = IP;
		return;
	}

	public function getPORT():Number {
		return PORT;
	}

	private function setPORT(PORT:Number):Void {
		this.PORT = PORT;
		return;
	}

	public function doCommunication():Boolean {
				
		//TODO para laburar sin el server
		if(Communication.DUMMY) {
			onConnect(false);
			return true;
		} else {
			return super.connect(this.getIP(), this.getPORT());
		}
	}; //fin función
	
	private function getData():Void {
		var root:Communication = this;
		var parser:TextParserListener= new TextParserListener();
		parser.parseError=function():Void {
			trace("Communication | getData | parseError");
		};
		parser.parseFinished= function(text:String):Void {
			var t:String = text;
			var divisor:Array = t.split("\n");
			for (var i:Number=0; i< divisor.length; i++) {
				var atts:Array= divisor[i].split("|");
				for(var j:Number=0; j < atts.length; j++){
					var values:Array = atts[j].split("=");
					switch(values[0]){
						case "IP":
						root.setIP(values[1]);
						break;
						
						case "PORT":
						root.setPORT(values[1]);
						break;
						
						case "DEMO":
						Communication.DUMMY = values[1];
						break;
					};
					if(root.getIP() && root.getPORT()) root.doCommunication();
				};
										
			}
			
		};
		var textParser:TextParser = new TextParser("data.zro", parser);	
	};
	
	//ACTIONS
	public function sendAction(act:XMLAction):Void {
		trace("\n--- Communication.as | sendAction() name= "+act.getName()+"\n"+act.toXML());
		
		Communication.DUMMY ? onXML(new XML(act.toXML())) : super.send(new XML(act.toXML())) ;
		return;
	};

	//
	//

	public function onXML(doc:XML):Void {
		trace("\nnew data arraive\n");
		trace(doc);
		trace("--")
		doc.ignoreWhite = true;
		try {
			listener.communicationEvent(CommunicationEventFactory.getCommunicationEvent(doc));
		} catch (e) {
			trace("Communication | onXML | Error");
			
		};
		return;
	}

	public function onConnect(s:Boolean):Void {
					
		if(s){
			HCC.findThemes();
			HCC.findDevices();
					
						
		} else {
			//APAGAR LA GUI
			trace("Communication.as --  Apagar la gui por fallo de conexion");
			trace("Communication.as -- Creando temas y dispositivos falsos");
			
			//TODO esto no va en la versión con server
			if(Communication.DUMMY){
				//dummyThemes
				var dummyThemes:String="";
				dummyThemes +="<action name='getThemes'>";
				dummyThemes += "<theme id='1' name='Tema 1' index='1' icon='cache_32.png' favorite='true' />";
				dummyThemes += "<theme id='2' name='Tema 2' index='2' icon='colors_32.png' favorite='false' />";
				dummyThemes += "<theme id='3' name='Tema 3' index='3' icon='file-manager_32.png' favorite='true' />";
				dummyThemes += "</action>";
				this.onXML(new XML(dummyThemes));
				
				//dummyDevices
				var dummyDevices:String ="";
				dummyDevices += "<action name='getArtifacts'>";
				
				dummyDevices += "<artifact id='11' type='dimmer' artifactName='Light1' state='240' group='living' />";
				dummyDevices += "<artifact id='12' type='dimmer' artifactName='Light2' state='230' group='living' />";
				dummyDevices += "<artifact id='21' type='rgb' artifactName='RGBLight1' state='240,50,50' group='living' />";
				dummyDevices += "<artifact id='22' type='rgb' artifactName='RGBLight2' state='255,255,0' group='living' />";
				dummyDevices += "<artifact id='3' type='lock' artifactName='door' state='off' group='living' />";
				dummyDevices += "<artifact id='41' type='blind' artifactName='curtain1' state='4' group='living' />";
				dummyDevices += "<artifact id='42' type='blind' artifactName='curtain2' state='8' group='living' />";
							
				dummyDevices += "</action>";
				this.onXML(new XML(dummyDevices));
				
				var o = new Object();
				o.onKeyDown = function():Void {
					if(Key.getAscii() == "112"){
						var dummyPerson:String = "";
						dummyPerson += "<action name='access' id='1' type='unknown' />"
						Communication.getInstance().onXML(new XML(dummyPerson));
					}
					return;
				}
				Key.addListener(o);
			}
		}

	};
		
};